#!/usr/bin/env python3
import os
import sys
import json
import random

def Get(path, headPath=""):
    for i in os.listdir(path):
        head = f"{headPath}/{i}"
        filePath = f"{path}/{i}"
        if os.path.isdir(filePath):
            Get(filePath, head)
            continue
        if os.path.isfile(filePath):
            pathList.append(head)
            continue


pathList = []
tempPath = f"/tmp/deb-to-squashfs-{random.randint(0, 100000)}"
os.system(f"dpkg -x '{sys.argv[1]}' '{tempPath}'")
os.system(f"dpkg -e '{sys.argv[1]}' '{tempPath}/DEBIAN'")
with open(f"{tempPath}/DEBIAN/control", "r") as file:
    while True:
        things = file.readline()
        if things == "":
            break
        if "Depends: " in things:
            with open(f"{tempPath}/depend.json", "w") as file:
                dependList = things.replace("Depends: ", "").replace(" ", "").replace("\n", "").split(",")
                file.write(json.dumps(dependList))
                break
if "--unnet" in sys.argv:
    os.makedirs(f"{tempPath}/DependDeb")
    newDepend = ""
    for i in dependList:
        if "|" in i:
            i = i.split("|")[0]
        newDepend += f"'{i}' "
    os.system(f"cd '{tempPath}/DependDeb' && apt download {newDepend}")
    if "--pack" in sys.argv:
        for i in os.listdir(f"{tempPath}/DependDeb"):
            if ".deb" in i:
                os.system(f"dpkg -x '{tempPath}/DependDeb/{i}' '{tempPath}'")
        os.system(f"rm -rf '{tempPath}/DependDeb/'")
if os.path.exists(f"{tempPath}/DEBIAN/postinst") or os.path.exists(f"{tempPath}/DEBIAN/preinst") or os.path.exists(f"{tempPath}/DEBIAN/prerm") or os.path.exists(f"{tempPath}/DEBIAN/postrm"):
    pass
os.system(f"rm -rf '{tempPath}/DEBIAN'")
#os.system()
Get(tempPath)
#print(pathList)
# 创建配置文件
with open(f"{tempPath}/filelist.json", "w") as file:
    file.write(json.dumps(pathList))
os.system(f"mksquashfs '{tempPath}' '{sys.argv[2]}' -noappend -comp xz")
os.system(f"rm -rf '{tempPath}'")